package com.smart.thrift.base;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.json.JSONUtil;

import java.util.Map;
import java.util.Objects;

public class DefaultSerializer implements ThriftSerializer {

    private static final String ARG = "arg";

    @Override
    public String serializeParameter(Object param) {
        if (Objects.isNull(param)) {
            return "";
        }
        String result = null;
        Class<?> type = param.getClass();
        if (ClassUtil.isBasicType(type)) {
            result = Convert.toStr(param);
        } else if (BeanUtil.isBean(type) || ClassUtil.isAssignable(Map.class, type)) {
            result = JSONUtil.toJsonStr(param);
        } else {
            result = JSONUtil.toJsonStr(Dict.create().set(ARG, param));
        }
        return result;
    }

    @Override
    public <T> T deserializeParameter(String paramStr, Class<T> paramType) {
        if (Objects.isNull(paramStr)) {
            return null;
        }
        T result = null;
        if (ClassUtil.isBasicType(paramType)) {
            result = Convert.convert(paramType, paramStr);
        } else if (BeanUtil.isBean(paramType) || ClassUtil.isAssignable(Map.class, paramType)) {
            result = JSONUtil.toBean(paramStr, paramType);
        } else {
            result = Convert.convert(paramType, JSONUtil.toBean(paramStr, Map.class).get(ARG) );
        }
        return result;
    }

    @Override
    public String serializeReturnValue(Object returnValue) {
        return serializeParameter(returnValue);
    }

    @Override
    public <T> T deserializeReturnValue(String returnStr, Class<T> returnType) {
        return deserializeParameter(returnStr, returnType);
    }
}
